var WxParse = require('../../../../wxParse/wxParse.js');
var HtmlParser = require('../../../../utils/htmlParseUtil.js');
var app = getApp();
var that;
Page({
  data: {
    item: {}, //详情
    isCollect: false,//是否被收藏
    remind: "加载中",
    id: ''
  },

  onLoad: function (options) {
    that = this;
    that.setData({ remind: '加载中'});
    that.getContent(options.id || 9364716);
  },
  onHide: function () {
    this.setData({ remind: '' });
  },

  getContent: function (id) {
    app.douban.findOneReviewHtml(id).then(function(res){
      parseStory(id, res, false);
    }, function(err){
      getReview(id);
      console.log("加载html数据失败，请稍后重试");
    });
  },
  previewImgEvent: function (e) {
    var src = e.currentTarget.dataset.src;
    if (src && src.length > 0) {
      wx.previewImage({
        urls: [src]
      });
    }
  },
});

function $(html) {
  return new HtmlParser(html);
};

function getReview(id){
  app.douban.findOneReview(id).then(function (res) {
      var content = res.content;
      var item = {
        title:res.title,
        updated_at: res.updated_at,
        useful_count: res.useful_count,
        useless_count: res.useless_count,
        rating: res.rating.value,
        author: res.author['name'],
        avatar: res.author['avatar'],
        bio: res.updated_at,
        content: parseStoryContent($(content.replace(/div/g, "p")))
      }
      that.setData({ item: item });
      that.setData({ remind: '' });
    }, function (err) {
      that.setData({ remind: '404' });
      console.log("加载api数据失败，请稍后重试");
    }, function(){
      wx.hideLoading();
    });
};

/**
 * 解析story对象的body部分
 * @param {string} html body的html文本
 * @param {boolean} isDecode 是否需要unicode解析
 * @return {object} 解析后的对象
 */
function parseStory(id, html, isDecode) {
  var $html = $(html);
  var title = getArrayContent($html.tag("h1").attr('class', 'title').match());
  var author = getArrayContent($(getArrayContent($html.tag("div").attr('class', 'user-title').match())).tag("span").match());
  var avatar = null;
  var avatarStr = $(getArrayContent($html.tag("div").attr('class', 'user-title').match())).tag("img");
  if(avatarStr && avatarStr.html){
    var imgReg = /<img.*?(?:>|\/>)/gi;
    var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    var arr = avatarStr.html.match(imgReg);
    if(arr.length >0){
      avatar = (arr[0].match(srcReg))[1];
    }
  }
  var timestamp = getArrayContent($html.tag("div").attr('class', 'timestamp').match());
  var content = getArrayContent($html.tag("div").attr('id', 'content').match());
  if (!content){
    getReview(id);
    return;
  }
  var contentArr = parseStoryContent($(content.replace(/div/g, "p")), isDecode);
  that.setData({
    item: {
      title: title,
      content: contentArr,
      author: author,
      avatar: avatar,
      bio: timestamp
    }
  });
  that.setData({ remind: '' });
}

/**
 * 解析文章内容
 * @param {string} $story htmlparser对象
 * @param {boolean} isDecode 是否需要unicode解析
 * @returb {object} 文章内容对象
 */
function parseStoryContent($story, isDecode) {
  var content = [];
  var ps = $story.tag('p').match();
  var p, strong, img, blockquote, em;
  if (ps && ps.length != 0) {
    for (var i = 0, len = ps.length; i < len; i++) {
      p = transferSign(ps[i]); //获取<p>的内容 ,并将特殊符号转义
      if (!p || p.isEmpty())
        continue;

      img = getArrayContent((p.jhe_ma('img', 'src')));
      strong = getArrayContent(p.jhe_om('strong'));
      em = getArrayContent(p.jhe_om('em'));
      blockquote = getArrayContent(p.jhe_om('blockquote'));

      if (!img.isEmpty()) { //获取图片
        content.push({ index: i, type: 'img', value: img });
      }
      else if (isOnly(p, strong) || p.indexOf("font-weight: bold") != -1) { //获取加粗段落<p><strong>...</strong></p>
        strong = decodeHtml(p, isDecode);
        if (!strong.isEmpty())
          content.push({ index: i, type: 'pstrong', value: strong });
      }
      else if (isOnly(p, em)) { //获取强调段落 <p><em>...</em></p>
        em = decodeHtml(p, isDecode);
        if (!em.isEmpty())
          content.push({ index: i, type: 'pem', value: em });
      }
      else if (isOnly(p, blockquote)) { //获取引用块 <p><blockquote>...</blockquote></p>
        blockquote = decodeHtml(p, isDecode);
        if (!blockquote.isEmpty())
          content.push({ index: i, type: 'blockquote', value: blockquote });
      }
      else { //其他类型 归类为普通段落 ....太累了 不想解析了T_T
        p = decodeHtml(p, isDecode);
        if (!p.isEmpty())
          content.push({ index: i, type: 'p', value: p });
      }
    }
  }else{
    //已br换行
    var htmlStr = $story.html;
    var htmlArr = htmlStr.split("<br>");
    if (htmlArr.length > 0){
      htmlArr.forEach(function(item){
        if(item){
          content.push({ index: 1, type: 'p', value: decodeHtml(transferSign(item), isDecode)});
        }
      });
    }else{
      content.push({ index: 1, type: 'p', value: decodeHtml(transferSign(htmlStr), isDecode) });
    }
  }
  return content;
}

/**
 * 取出多余或者难以解析的html并且替换转义符号
 */
function decodeHtml(value, isDecode) {
  if (!value) return '';
  value = value.replace(/<[^>]+>/g, '')
    .replace(/&nbsp;/g, ' ')
    .replace(/&ldquo;/g, '"')
    .replace(/&rdquo;/g, '"').replace(/&middot;/g, '·');
  if (isDecode)
    return decodeUnicode(value.replace(/&#/g, '\\u'));
  return value;

}

/**
 * 解析段落的unicode字符，主题日报中的内容又很多是编码过的
 */
function decodeUnicode(str) {
  var ret = '';
  var splits = str.split(';');
  for (let i = 0; i < splits.length; i++) {
    ret += spliteDecode(splits[i]);
  }
  return ret;
};

/**
 * 解析单个unidecode字符
 */
function spliteDecode(value) {
  var target = value.match(/\\u\d+/g);
  if (target && target.length > 0) { //解析类似  "7.1 \u20998" 参杂其他字符
    target = target[0];
    var temp = value.replace(target, '{{@}}');
    target = target.replace('\\u', '');
    target = String.fromCharCode(parseInt(target));
    return temp.replace("{{@}}", target);
  } else {
    // value = value.replace( '\\u', '' );
    // return String.fromCharCode( parseInt( value, '10' ) )
    return value;
  }
}

/**
 * 获取数组中的内容（一般为第一个元素）
 * @param {array} arr 内容数组
 * @return {string} 内容
 */
function getArrayContent(arr) {
  if (!arr || arr.length == 0) return '';
  return arr[0];
}

function isOnly(src, target) {
  return src.trim() == target;
}

/**
 * 判断目标是否是函数
 * @param {mixed} val
 * @returns {boolean}
 */
function isFunction(val) {
  return typeof val === 'function';
}

/**
 * 修正图片url，将pic1和pic2改为pic4
 * @param data
 * @returns {*}
 */
function correctData(data) {
  if (("top_stories" in data)) {
    var top_stories = data.top_stories;
    data.top_stories = top_stories;
  }

  var stories = data.stories;
  for (var i = 0; i < stories.length; i++) {
    if (("images" in stories[i])) {
      var s = stories[i].images[0];
      stories[i].images[0] = s;
    }
  }

  data.stories = stories;
  return data;
}

/**
 * 将转义字符转为实体
 * @param data
 * @returns {*}
 */
function transferSign(data) {
  data = data.replace(/&ndash;/g, "–");
  data = data.replace(/&mdash;/g, "—");
  data = data.replace(/&hellip;/g, "…");
  data = data.replace(/&bull;/g, "•");
  data = data.replace(/&rsquo;/g, "’");
  data = data.replace(/&ndash;/g, "–");
  data = data.replace(/&quot;/g, '"');
  data = data.replace(/&#x27;/g, '\'');
  return data;
}